<template>
  <div class="container">
    <div class="app-container">
      <el-row type="flex">
        <span style="margin-top: 10px;margin-left: 15px;margin-top: 25px;">楼宇名称：</span>
        <el-input v-model="buildparams.name" style="width: 200px;margin-right: 10px;margin-top: 15px;" placeholder="请输入楼宇名称" />
        <el-button size="mini" type="primary" style="margin-top: 15px;border-radius: 5px;" @click="queryBuild">查 询</el-button>
      </el-row>
      <el-row>
        <el-button style="margin-top: 15px; margin-left: 15px;border-radius: 5px;" size="mini" type="primary" @click="showDialog = true">添加楼宇</el-button>
      </el-row>
      <el-table v-loading="loading" :data="list">
        <el-table-column label="序号" type="index" align="center" width="200" />
        <el-table-column label="楼宇名称" prop="name" align="center" width="200" />
        <el-table-column label="层数" prop="floors" align="center" width="200" />
        <el-table-column label="在管面积(m²)" prop="area" align="center" width="200" />
        <el-table-column label="物业费(元/m²)" prop="propertyFeePrice" align="center" width="200" />
        <el-table-column label="状态" prop="status" align="center" width="200">
          <template v-slot="{row}">
            <span>{{ row.status==0? '空置中' : '租赁中' }}</span>
          <!-- <span>{{ row.status===0? '空置中' : '租赁中' }}</span> -->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" prop="demoFlag">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <!-- 分页组件 -->
      <el-row style="height: 80px;" type="flex" justify="end" align="middle">
        <el-pagination
          :page-sizes="[10,20,50,100]"
          :page-size="buildparams.pagesize"
          :current-page="buildparams.page"
          :total="buildparams.total"
          layout="prev, pager, next, jumper, total"
          @current-change="changePage"
          @size-change="changecurrent"
        />
      </el-row>
      <el-dialog class="addDialog" width="550px" :visible.sync="showDialog" @close="btnCancel">
        <el-form ref="buildForm" :model="buildForm" :rules="rules" style="width: 100%; padding:0 40px;">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="buildForm.name" placeholder="请输入楼宇名称" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="buildForm.floors" placeholder="请输入楼宇层数" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="buildForm.area" placeholder="请输入在管面积">
              <template slot="append">m²</template>
            </el-input>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="buildForm.propertyFeePrice" placeholder="请输入物业费">
              <template slot="append">元/m²</template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="end">
          <el-button size="mini" style="border-radius: 5px;" @click="btnCancel">取消</el-button>
          <el-button type="primary" size="mini" style="border-radius: 5px;" @click="btnOK">确定</el-button>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addFlooringAPI, delFlooringAPI, getFloorAPI, getFloorDetailAPI, updateFlooringAPI } from '@/api/BuildingManagement'

export default {
  name: 'BuildingManagement',
  data() {
    return {
      searchQuery: '',
      list: [],
      loading: false,
      buildparams: {
        name: '',
        page: 1,
        pageSize: 10,
        total: 0
      },
      showDialog: false,
      buildForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      rules: {
        name: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }],
        floors: [{ required: true, message: '请输入楼层数', trigger: 'blur' },
          { pattern: /^(1[0-9]|20|1)$/, message: '楼层最大数为20', trigger: 'blur' }
        ],
        area: [{ required: true, message: '在管面积不能为空', trigger: 'blur' }],
        propertyFeePrice: [
          { required: true, message: '物业费不能为空', trigger: ['blur', 'input'] },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('物业费不能为空'))
              } else if (!/^\d*\.?\d+$/.test(value)) {
                callback(new Error('物业费必须为数字值'))
              } else if (parseFloat(value) < 0) {
                callback(new Error('物业费不能为负数'))
              } else if (value.toString().replace('.', '').length > 8) {
                callback(new Error('物业费不能超过8位数'))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'input']
          }
        ]
      }
    }
  },
  created() {
    this.getFloor()
  },
  methods: {
    async getFloor() {
      const { rows, total } = await getFloorAPI(this.buildparams) // 使用传入的 params 调用 API
      this.list = rows
      this.buildparams.total = total
    },
    async changePage(newPage) {
      this.loading = true
      this.buildparams.page = newPage // 赋值当前页码
      await this.getFloor()
      this.loading = false
    },
    async changecurrent(newcurrent) {
      this.loading = true
      this.buildparams.pageSize = newcurrent
      await this.getFloor()
      this.loading = false
    },
    async queryBuild() {
      this.loading = true
      await this.getFloor()
      this.loading = false
    },
    async btnOK() {
      await this.$refs.buildForm.validate()
      // 如果有ID，编辑；没ID，添加
      if (this.buildForm.id) {
        const res = await updateFlooringAPI({
          name: this.buildForm.name,
          floors: this.buildForm.floors,
          area: this.buildForm.area,
          propertyFeePrice: this.buildForm.propertyFeePrice,
          id: this.buildForm.id
        })
        console.log(res)
        this.$message.success('编辑成功')
        this.btnCancel()
        this.getFloor()
      } else {
        const res = await addFlooringAPI(this.buildForm)
        this.$message.success('增加成功')
        console.log(res)
        this.btnCancel()

        this.getFloor()
      }
    },
    async btnCancel() {
      this.buildForm = {
        id: '',
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      }
      this.$refs.buildForm.resetFields()
      this.showDialog = false
    },
    async handleEdit(index, row) {
      const res = await getFloorDetailAPI(row.id)
      this.buildForm = res
      this.showDialog = true
    },
    async handleDelete(index, row) {
      try {
        // 使用 Element UI 的 MessageBox 弹出确认对话框
        await this.$confirm('确定要删除该楼宇吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 如果用户点击“确定”，则执行删除操作
        await delFlooringAPI(row.id)
        this.$message.success('删除成功')
        this.getFloor()
      } catch (error) {
        // 如果用户点击“取消”，则不执行任何操作
        console.log('删除操作已取消')
      }
    }
  }
}
</script>

